package interactive

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// SelectOne 单选
func SelectOne(message string, options []string) (string, error) {
	var scanner = bufio.NewScanner(os.Stdin)

	var mapping = map[string]struct{}{}
	for _, item := range options {
		mapping[item] = struct{}{}
	}

	for {
		fmt.Printf("%s，您需要在选项[%v]中选择一个，输入选项名称或序号[1-%d]: ", message, strings.Join(options, "/"), len(options))
		if scanner.Scan() {
			if nil != scanner.Err() {
				return "", scanner.Err()
			}

			var selected = strings.TrimSpace(scanner.Text())

			// 检查选项
			if _, ok := mapping[selected]; ok {
				return selected, nil
			}

			// 解析序号
			if v, err := strconv.Atoi(selected); nil == err {
				if 1 <= v && v <= len(options) {
					return options[v-1], nil
				}
			}
		}
	}
}
